import Taro, { Component } from '@tarojs/taro';
import { View, Text, Picker } from '@tarojs/components';
import { AtForm, AtInput, AtButton, AtImagePicker } from 'taro-ui';
import './tianjiayinghangka.css';
import app from '../../../../main.js'

export default class Tianjiayinghangka extends Component {
  config = {
    navigationBarTitleText: '添加银行卡'
  }
  constructor() {
    super(...arguments)
    this.state = {
      doctor_bank: {
        id: '',
        bank_account: '',
        bank_name: '',
        bank_branch:'',
        bank_number: '',
        bank_pic: [],
        province: '',
        city: '',
        district: ''
      },
      banks: []
    }
  }

  getDoctorBank() {
    var me = this;
    app.get('doctor_bank/getByToken', {}, function(res) {
      if (res.data.status == 200 && !app.isEmpty(res.data.result)) {
        var doctor_bank = res.data.result;
        try {
          doctor_bank.bank_pic = !app.isEmpty(doctor_bank.bank_pic) ? JSON.parse(doctor_bank.bank_pic) : [];
        } catch (error) {
          doctor_bank.bank_pic = [];
        }
        me.setState({
          doctor_bank: doctor_bank
        })
      }
    })
  }

  getBanks() {
    var me = this;
    app.get('doctor_bank/banks', {}, function(res) {
      me.setState({
        banks: res.data.result.list
      })
    })
  }

  onChangeBank(e) {
    var value = e.detail.value;
    var doctor_bank = this.state.doctor_bank;
    doctor_bank.bank_name = this.state.banks[value];
    this.setState({
      doctor_bank: doctor_bank
    })
  }

  onChangeAddress(e) {
    var value = e.detail.value;
    var doctor_bank = this.state.doctor_bank;
    doctor_bank.province = value[0];
    doctor_bank.city = value[1];
    doctor_bank.district = value[2];
    this.setState({
      doctor_bank: doctor_bank
    })
  }

  handleChange(name, v) {
    var names = name.split('.');
    var n = names[0];
    var temp = this.state;
    for(var i = 0; i < names.length - 1; i++) {
        temp = temp[names[i]];
    }
    temp[names[i]] = v;
    this.setState({n: temp[names[i]]});
  }

  onChangeImage(files, operationType, index) {
    let me = this;
    if (operationType == 'add') {
      Taro.showLoading({
        title: '上传中...',
        mask: true
      });
      Taro.uploadFile({
        url: app.apiUri + '/admin/upload/image',
        filePath: files[files.length - 1]['url'],
        name: 'file',
        formData: {
          name: 'file'
        },
        success(res) {
          Taro.hideLoading();
          if (res.statusCode == 413) {
            app.toast('文件过大，请重新上传');
            return;
          }
          let data = JSON.parse(res.data);
          if (data.status == 200) {
            let item = {url: app.getPath(data.result)}
            var doctor_bank = me.state.doctor_bank;
            doctor_bank.bank_pic.push(item);
            me.setState({
              doctor_bank: doctor_bank
            })
          }
        }
      })
    } else if (operationType == 'remove') {
      var doctor_bank = me.state.doctor_bank;
      doctor_bank.bank_pic.splice(index, 1);
      me.setState({
        doctor_bank: doctor_bank
      });
    }
  }

  onImageClick(index, file) {
    app.prviewImage(file.url, [file.url]);
  }

  onSubmit() {
    var me = this;
    var data = this.state.doctor_bank;
    console.log(data)
    if (app.isEmpty(data.bank_account)) {
      app.toast('请输入持卡人姓名');
      return;
    }
    if (app.isEmpty(data.bank_number)) {
      app.toast('请输入银行卡号');
      return;
    }
    if (app.isEmpty(data.province)) {
      app.toast('请选择开户地点');
      return;
    }
    if (app.isEmpty(data.bank_name)) {
      app.toast('请选择开户行');
      return;
    }
    if (app.isEmpty(data.bank_branch)) {
      app.toast('请输入银行支行');
      return;
    }
    if (app.isEmpty(data.bank_pic)) {
      app.toast('请上传银行卡正面照');
      return;
    }
    data.bank_pic = JSON.stringify(data.bank_pic);
    Taro.showLoading();
    app.post('doctor_bank/save', data, function(res) {
      if (res.data.status == 200) {
        Taro.hideLoading();
        app.toast('保存成功');
        setTimeout(() => {
          Taro.navigateBack({
            delta: 1
          })
        }, 1000)
      } else {
        app.toast('保存失败');
        Taro.hideLoading();
      }
    })
  }
  
  componentDidMount() { 
    this.getBanks();
    this.getDoctorBank();
  }

  render() {
    return (
      <View className='index'>
        <AtInput
          title='持卡人姓名'
          type='text'
          placeholder='请填写银行卡所有人'
          value={this.state.doctor_bank.bank_account}
          onChange={this.handleChange.bind(this, 'doctor_bank.bank_account')}
        />
        <AtInput
          title='银行卡号'
          name='kh'
          type='number'
          placeholder='请填写卡号'
          value={this.state.doctor_bank.bank_number}
          onChange={this.handleChange.bind(this,'doctor_bank.bank_number')}
        />
        <View className='item'>
          <Text className='item_label'>开户地点</Text>
          <Picker mode='region'onChange={this.onChangeAddress.bind(this)}>
            <View className='item_value'>
              {
                this.state.doctor_bank.province ? (this.doctor_bank.province+this.doctor_bank.city+this.doctor_bank.district) : "请选择开户地"
              }
            </View>
          </Picker>
        </View>
        <View className='item'>
          <Text className='item_label'>开户行</Text>
          <Picker mode='selector' range={this.state.banks} onChange={this.onChangeBank.bind(this)}>
            <View className='item_value'>
              {
                this.state.doctor_bank.bank_name ? this.state.doctor_bank.bank_name : "请选择开户行"
              }
            </View>
          </Picker>
        </View>
        
        <AtInput
          name='value'
          title='银行支行'
          type='text'
          placeholder='请填写银行支行'
          value={this.state.doctor_bank.bank_branch}
          onChange={this.handleChange.bind(this,'doctor_bank.bank_branch')}
        />



        <View className='pic'>
          <View className='pic_label'>请上传银行卡正面照</View>
          <AtImagePicker
            count={1}
            files={this.state.doctor_bank.bank_pic}
            onChange={this.onChangeImage.bind(this)}
            onImageClick={this.onImageClick.bind(this)}
          />
        </View>
        <View className='bottom'>
          <AtButton type='primary' formType='submit' circle  onClick={this.onSubmit.bind(this)} >提交</AtButton>
        </View>
      </View>
    )
  }
}